import {
  Button,
  Col,
  DatePicker,
  Form,
  Input,
  Modal,
  PageHeader,
  Popconfirm,
  Row,
  Select,
  Space,
  Spin,
  Table,
} from 'antd';
import { CheckOutlined, PlusOutlined, RollbackOutlined } from '@ant-design/icons';
import moment from 'moment';
import { useLocation, useNavigate } from 'react-router-dom';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { validateRules, validators } from 'src/lib/jValidate/JValidateRules';
import basicService from '../../../service/basic/basic.service';
import { useRequest } from '../../../lib/request';
import useDebounceSelect from '../../../hooks/common/useDebounceSelect/useDebounceSelect';

const { Option } = Select;
const colSpan = 6;
const rowOption = {
  gutter: 60,
  // justify: 'center'
};

const initialSearchParams = {
  // 是否重点推荐客户:0：否，1：是
  isSCust: '1',
  // 行业类型名称
  dataindustryName: '通用',
};

function DealerDetail(props) {
  const navigate = useNavigate();
  const location = useLocation();
  const [form] = Form.useForm();
  const [formDisabled, setFormDisabled] = useState(false);
  // 详情id
  const [id, setId] = useState('');
  // 详情id
  const [purchaseId, setPurchaseId] = useState('');
  // 标题名字：新增 编辑 详情
  const [titleType, setTitleType] = useState('');
  const [pageNum, setPageNum] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const params = {
    pageNum,
    pageSize,
    purchaseId,
  };
  const [
    {
      data = {
        list: [],
        total: 0,
      },
    },
    loading,
    query,
    setResponse,
  ] = useRequest(() => basicService.getDealerPurchaseList(params), [pageNum, pageSize, purchaseId]);
  //  添加采购信息form
  const [purchaseForm] = Form.useForm();
  // 采购form显示隐藏
  const [isModalVisible, setIsModalVisible] = useState(false);
  // 采购form月份是否禁用
  const [purchaseMonthDisabled, setPurchaseMonthDisabled] = useState(false);
  const fetchCoreEnterpriseList = useCallback((coreCustName, coreEnterpriseId) => {
    /**
     *  获取核心企业,用于下拉框选择核心企业
     *  @param id -核心企业id,只有初始化的时候才会传这个
     * */
    return basicService
      .getCoreEnterpriseList({
        id: coreEnterpriseId,
        coreCustName,
        pageNum: 1,
        pageSize: 50,
      })
      .then(({ success, data: coreEnterpriseData }) => {
        let options = [];
        if (success && coreEnterpriseData.list && coreEnterpriseData.list.length) {
          options = coreEnterpriseData.list.map((v) => ({
            label: v.coreCustName,
            value: v.id,
            corecustcode: v.coreCustCode,
          }));
        }
        return options;
      });
  }, []);
  // 下拉框组件参数
  const [coreEnterpriseOptions, setCoreEnterpriseOptions, coreEnterpriseFetcher, coreEnterpriseLoading] =
    useDebounceSelect({
      fetchOptions: fetchCoreEnterpriseList,
    });

  function coreEnterpriseSltChange(_, record) {
    /**
     * 核心企业下拉change
     * */
    // 修改核心企业统一信用代码
    form.setFieldsValue({
      coreCustCode: record.corecustcode,
    });
  }

  function backToList() {
    /**
     * 回到经销商列表
     * */
    navigate('/internetCommercialBank/dealer');
  }

  async function submitForm(value) {
    /**
     * 表单数值变化，提交表单
     * */
    let submitFormState;
    const newValue = {
      ...value,
      custCoopMonth: value.custCoopMonth.format('YYYYMM'),
      // coreCustId: value.coreCustId.value
    };
    if (id) {
      submitFormState = await submitUpdate(newValue);
    } else {
      submitFormState = await submitNew(newValue);
    }
    if (submitFormState) {
      backToList();
    }
  }

  async function addDealerPurchase(cgdCustId) {
    /**
     * 添加采购信息
     * */
    const { success: addDealerPurchaseState } = await basicService.addDealerPurchase({
      cgdCustId,
      purchaseInfoList: data.list.map((v) => ({
        custAmount: v.custAmount,
        custAmountMonth: v.custAmountMonth,
      })),
    });
    return addDealerPurchaseState;
  }

  async function submitNew(formData) {
    /**
     * 新增经销商
     * */
    const { success, data: submitNewData } = await basicService.addDealer({
      ...formData,
    });
    if (success) {
      // 继续新增采购信息
      if (data.list.length) {
        return await addDealerPurchase(submitNewData.cgdCustId);
      }
    }
    return success;
  }

  async function submitUpdate(formData) {
    /**
     * 修改经销商
     * */
    const { success, data: submitNewData } = await basicService.updateDealer({
      id,
      ...formData,
    });
    if (success) {
      // 继续新增采购信息
      if (data.list.length && submitNewData) {
        return await addDealerPurchase(submitNewData.cgdCustId);
      }
    }
    return success;
  }

  const titleTypeName = useMemo(() => {
    /**
     * 页面类型标题名（新增|编辑|详情）
     * */
    return (
      {
        add: '新增',
        edit: '编辑',
        detail: '详情',
      }[titleType] || ''
    );
  }, [titleType]);

  useEffect(() => {
    /* 设置标题、页面类型、表单的值 */
    const state = location.state;
    if (!state) {
      setTitleType('add');
      return;
    }
    const { type, detail } = state;
    if (type === 'detail' || type === 'edit') {
      setId(detail.id);
      setPurchaseId(detail.cgdCustId);
      form.setFieldsValue({
        agentCustCode: detail.agentCustCode,
        agentCustFrCode: detail.agentCustFrCode,
        agentCustFrName: detail.agentCustFrName,
        agentCustName: detail.agentCustName,
        coreCustAgentNo: detail.coreCustAgentNo,
        // 核心企业id
        coreCustId: detail.coreCustId,
        // 核心企业统一信用代码
        coreCustCode: detail.coreCustCode,
        // 合作月份
        custCoopMonth: moment(detail.custCoopMonth),
        dataindustryName: detail.dataindustryName,
        isSCust: detail.isSCust,
      });
      if (type === 'detail') {
        setFormDisabled(true);
      }
    }
    setTitleType(type || 'add');
  }, [form, location.state]);

  useEffect(() => {
    /* 查询核心企业选择框的option */
    if (location.state?.type === 'detail' || location.state?.type === 'edit') {
      fetchCoreEnterpriseList(null, location.state.detail.coreCustId).then((v) => {
        setCoreEnterpriseOptions(v);
      });
    }
  }, [fetchCoreEnterpriseList, location, setCoreEnterpriseOptions]);

  function addRecord() {
    /**
     * 添加采购信息打开对话框
     * */
    // 重置表单
    purchaseForm.resetFields(['custAmount', 'custAmountMonth']);
    setPurchaseMonthDisabled(false);
    setIsModalVisible(true);
  }

  function updatePurchaseConfirm(value) {
    /**
     * 添加或者修改采购确认
     * */
    const tempData = { ...data };
    const tempList = [...data.list];
    const purchaseDetail = {
      // 采购金额
      custAmount: value.custAmount * 1,
      // 采购月份
      custAmountMonth: value.custAmountMonth.format('YYYYMM'),
    };
    if (purchaseMonthDisabled) {
      // 编辑的时候
      tempList.find((v) => v.id === value.id).custAmount = purchaseDetail.custAmount;
      basicService.updateDealerPurchase({
        id: value.id,
        ...purchaseDetail,
      });
    } else {
      // 新增的时候
      // 不允许有重复的月份
      if (tempList.some((v) => v.custAmountMonth.replace('-', '') === purchaseDetail.custAmountMonth)) {
        Modal.error({
          title: '提示',
          content: `月份${purchaseDetail.custAmountMonth}已经存在，不可添加重复月份的数据`,
        });
        return;
      }
      tempList.push({
        id: new Date().getTime(),
        ...purchaseDetail,
      });
      tempData.total++;
    }
    tempData.list = tempList;
    setResponse({
      data: tempData,
    });
    setIsModalVisible(false);
  }

  function openEditPurchase(record) {
    /* 编辑采购信息打开话框 */
    purchaseForm.resetFields(['custAmount', 'custAmountMonth']);
    purchaseForm.setFieldsValue({
      id: record.id,
      custAmountMonth: moment(record.custAmountMonth),
      custAmount: record.custAmount,
    });
    setPurchaseMonthDisabled(true);
    setIsModalVisible(true);
  }

  async function delRow(rowId, index) {
    /**
     * 删除一行
     * */
    if (rowId) {
      const { success } = await basicService.deleteDealerPurchase(rowId);
      if (success) {
        query();
      }
    } else {
      // 添加的时候直接删除
      const tempData = { ...data };
      const tempList = [...tempData.list];
      tempList.splice(index, 1);
      tempData.list = tempList;
      setResponse(tempData);
    }
  }

  const columns = [
    {
      title: '序号',
      dataIndex: 'name',
      width: 60,
      render: (...record) => {
        return <span>{record[2] + 1}</span>;
      },
    },
    {
      title: '采购月份',
      dataIndex: 'custAmountMonth',
      width: 200,
    },
    {
      title: '采购金额（元）',
      width: 200,
      dataIndex: 'custAmount',
      // editable: titleType === 'edit',
      editable: true,
    },
  ];
  if (titleType === 'add' || titleType === 'edit') {
    columns.push({
      title: '操作',
      width: 140,
      fixed: 'right',
      render: (text, record, index) => (
        <Space size={10}>
          {(titleType === 'add' || titleType === 'edit') && (
            <>
              <span className="common-link" onClick={() => openEditPurchase(record)}>
                编辑
              </span>
              <Popconfirm title="确定要删除吗?" onConfirm={() => delRow(record.id, index)}>
                <span className="common-link">删除</span>
              </Popconfirm>
            </>
          )}
        </Space>
      ),
    });
  }

  return (
    <div className="common-detail-warp">
      <PageHeader title={`经销商管理${titleTypeName}`} />
      <Form
        form={form}
        name=""
        className="common-detail-form-wrap"
        layout="vertical"
        initialValues={initialSearchParams}
        onFinish={submitForm}
      >
        <Row {...rowOption}>
          <Col span={colSpan}>
            <Form.Item
              name="coreCustAgentNo"
              label="客户编码"
              rules={[
                {
                  required: true,
                },
                {
                  type: 'string',
                },
                {
                  max: 50,
                },
              ]}
            >
              <Input placeholder="请输入客户编码" allowClear disabled={formDisabled} />
            </Form.Item>
          </Col>
          <Col span={colSpan}>
            <Form.Item
              name="dataindustryName"
              label="行业类型"
              rules={[
                {
                  required: true,
                },
                {
                  type: 'string',
                },
              ]}
            >
              <Select disabled={formDisabled}>
                <Option value="通用">通用</Option>
                {/* <Option value="消费电子">消费电子</Option> */}
              </Select>
            </Form.Item>
          </Col>
          <Col span={colSpan}>
            <Form.Item
              name="agentCustName"
              label="经销商名称"
              rules={[
                {
                  type: 'string',
                },
                {
                  max: 50,
                },
              ]}
            >
              <Input placeholder="请输入经销商名称" allowClear disabled={formDisabled} />
            </Form.Item>
          </Col>
          <Col span={colSpan}>
            <Form.Item
              name="agentCustCode"
              label="经销商统一社会信用代码"
              rules={[
                {
                  type: 'string',
                },
                {
                  max: 50,
                },
              ]}
            >
              <Input placeholder="请输入经销商统一社会信用代码" allowClear disabled={formDisabled} />
            </Form.Item>
          </Col>
          <Col span={colSpan}>
            <Form.Item
              name="agentCustFrName"
              label="法人姓名"
              rules={[
                {
                  required: true,
                },
                {
                  type: 'string',
                },
                {
                  max: 50,
                },
              ]}
            >
              <Input placeholder="请输入法人姓名" allowClear disabled={formDisabled} />
            </Form.Item>
          </Col>
          <Col span={colSpan}>
            <Form.Item
              name="agentCustFrCode"
              label="法人身份证号码"
              rules={[
                {
                  required: true,
                },
                {
                  validator: (_, value) => {
                    return validators.IDCard(value)
                      ? Promise.resolve()
                      : Promise.reject(new Error('请输入合法的身份证号码'));
                  },
                },
              ]}
            >
              <Input placeholder="请输入法人身份证号码" allowClear disabled={formDisabled} />
            </Form.Item>
          </Col>
          <Col span={colSpan}>
            <Form.Item
              name="coreCustId"
              label="核心企业"
              rules={[
                {
                  required: true,
                  message: '请选择核心企业',
                },
              ]}
            >
              <Select
                showSearch
                filterOption={false}
                onSearch={coreEnterpriseFetcher}
                loading={coreEnterpriseLoading}
                notFoundContent={coreEnterpriseLoading ? <Spin size="small" /> : null}
                options={coreEnterpriseOptions}
                placeholder="请输入核心企业名称用以搜索"
                allowClear
                disabled={formDisabled || titleType === 'edit'}
                onSelect={coreEnterpriseSltChange}
              />
            </Form.Item>
          </Col>
          <Col span={colSpan}>
            <Form.Item
              name="coreCustCode"
              label="核心企业统一社会信用代码"
              rules={[
                {
                  required: true,
                  message: '请选择核心企业',
                },
              ]}
            >
              <Input disabled />
            </Form.Item>
          </Col>
          <Col span={colSpan}>
            <Form.Item
              name="custCoopMonth"
              label="合作月份"
              rules={[
                {
                  required: true,
                  message: '请选择合作月份',
                },
              ]}
            >
              <DatePicker picker="month" allowClear disabled={formDisabled} />
            </Form.Item>
          </Col>
          <Col span={colSpan}>
            <Form.Item
              name="isSCust"
              label="是否重点推荐客户"
              rules={[
                {
                  required: true,
                  message: '请选择',
                },
                {
                  max: 50,
                  type: 'string',
                },
              ]}
            >
              <Select disabled={formDisabled}>
                <Option value="1">是</Option>
                <Option value="0">否</Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <div className="common-detail-form-wrap">
        <Row className="common-table-operation-wrap">
          <Col>
            <Space size={30}>
              {(titleType === 'add' || titleType === 'edit') && (
                <Button type="primary" icon={<PlusOutlined />} onClick={addRecord}>
                  新增
                </Button>
              )}
            </Space>
          </Col>
        </Row>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={data?.list || []}
          loading={loading}
          scroll={{
            x: 'max-content',
          }}
          pagination={{
            position: ['bottomRight'],
            showSizeChanger: true,
            current: pageNum,
            total: data?.total || 0,
            showTotal: (total) => `共 ${total} 条数据`,
            onChange: (num, size) => {
              let tempNum = num;
              if (size !== pageSize) {
                setPageSize(size);
                tempNum = 1;
              }
              setPageNum(tempNum);
            },
          }}
        />
        <Row justify="center" className="pt60">
          <Space size={30}>
            {!formDisabled && (
              <Button type="primary" icon={<CheckOutlined />} onClick={form.submit}>
                提交
              </Button>
            )}
            <Button
              icon={<RollbackOutlined />}
              onClick={() => {
                navigate(-1);
              }}
            >
              返回
            </Button>
          </Space>
        </Row>
      </div>
      <Modal
        title="采购信息"
        className="common-modal-detail-warp"
        visible={isModalVisible}
        onOk={purchaseForm.submit}
        onCancel={() => {
          setIsModalVisible(false);
        }}
      >
        <Form
          form={purchaseForm}
          className=""
          layout="vertical"
          initialValues={initialSearchParams}
          onFinish={updatePurchaseConfirm}
        >
          <Form.Item hidden name="id">
            <Input />
          </Form.Item>
          <Form.Item
            name="custAmountMonth"
            label="采购月份"
            rules={[
              {
                required: true,
                message: '请选择采购月份',
              },
            ]}
          >
            <DatePicker picker="month" placeholder="请输入采购月份" allowClear disabled={purchaseMonthDisabled} />
          </Form.Item>
          <Form.Item
            name="custAmount"
            label="采购金额（元）"
            rules={[
              {
                required: true,
                message: '请输入采购金额',
              },
              {
                pattern: validateRules.money,
                message: '请输入正确的金额',
              },
              {
                validator: (_, value) => {
                  return value * 1 <= 9999999999
                    ? Promise.resolve()
                    : Promise.reject(new Error('金额最大值为9999999999'));
                },
              },
            ]}
          >
            <Input placeholder="请输入采购金额" allowClear />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

export default DealerDetail;
